#include "qfindview.h"

#include "qfindbar.h"

#include "../include/pageinterface.h"
#include "../include/qfindresult.h"

#include <QVBoxLayout>
#include <QHeaderView>

QFindView::QFindView(QWidget *parent) :
    QWidget(parent),
    m_resultTree(new QTreeWidget),
    m_findBar(new QFindBar)
{

    QVBoxLayout *v=new QVBoxLayout;
    v->setMargin(0);
    v->setSpacing(0);
    v->addWidget(m_findBar);
    v->addWidget(m_resultTree);
    this->setLayout(v);

    m_resultTree->header()->setVisible(false);
    m_resultTree->setFrameStyle(QFrame::NoFrame);

    connect(m_findBar,SIGNAL(search(QString,bool,bool)),this,SLOT(search(QString,bool,bool)));
    connect(m_findBar,SIGNAL(clear()),this,SLOT(clear()));
}

void QFindView::search(const QString &text, bool sensitive, bool whole)
{
    clear();
    if(text=="")
    {
        return;
    }
    QFindResult *result;
    foreach(PageInterface *page,m_pages)
    {
        result=page->search(text,sensitive,whole);
        if(result!=NULL)
        {
            QTreeWidgetItem *item;
            if(result->m_results.size()>0)
            {
                item=new QTreeWidgetItem(m_resultTree);
                item->setText(0,result->m_page);
                foreach(FindResult *r,result->m_results)
                {
                    QTreeWidgetItem *it=new QTreeWidgetItem(item);
                    it->setText(0,r->value("name")+":"+r->value("value"));
                    m_items.insert(it,r);
                }
                m_results.append(result);
            }
            else
            {
                delete result;
            }

        }
    }
}

void QFindView::addPage(PageInterface *page)
{
    m_pages.append(page);
}

void QFindView::clear()
{
    foreach(QFindResult *r,m_results)
    {
        qDeleteAll(r->m_results);
        r->m_results.clear();
    }

    qDeleteAll(m_results);
    m_results.clear();
    m_resultTree->clear();
    m_items.clear();
}
